package com.letoken.platform.job.redis;

import com.letoken.platform.pub.util.BeanUtil;
import com.letoken.platform.job.constant.RedisConstant;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @author letokenlabs
 * @date 2022/12/19$
 */
public class EmailSendRedis {

    private StringRedisTemplate stringRedisTemplate;


    private EmailSendRedis() {
        stringRedisTemplate = BeanUtil.getBean(StringRedisTemplate.class);
    }

    private enum Singleton {
        INSTANCE;
        private EmailSendRedis instance;

        // JVM会保证此方法绝对只调用一次
        Singleton() {
            instance = new EmailSendRedis();
        }
    }

    public static EmailSendRedis me() {
        return EmailSendRedis.Singleton.INSTANCE.instance;
    }

    /**
     * 判断邮件是否已发送（有效期内只发一次）
     * @param key
     * @return
     */
    public boolean isSending(String key){
        Object status = stringRedisTemplate.opsForValue().get(String.format("%s:%s", RedisConstant.JOB_EMAIL_SEND, key));
        if(status!=null)
            return status.toString().equals("1");
        return false;
    }


    /**
     * 设置邮件发送有效期（防止重复发送）
     * @param key
     * @param status
     * @param expire_min
     */
    public void setSending(String key, boolean status, int expire_min) {
        stringRedisTemplate.opsForValue().set(String.format("%s:%s", RedisConstant.JOB_EMAIL_SEND, key),
                status ? "1" : "0", expire_min, TimeUnit.MINUTES);
    }
}
